package cn.edu.swu.shop;

import cn.edu.swu.auth.UserLoginService;
import cn.edu.swu.auth.UserRepo;
import cn.edu.swu.book.Book;
import cn.edu.swu.book.BookRepo;
import cn.edu.swu.book.CartItem;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(urlPatterns = {"/user/shopping"})
public class ShoppingServlet extends HttpServlet {

    private BookRepo bookRepo = new BookRepo();
    private UserRepo userRepo = new UserRepo();
    private UserLoginService userLoginService = new UserLoginService(userRepo);

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();

        // 获取uid
        Integer uid = (Integer) session.getAttribute("uid");
        out.println("<script>console.log('获取到的用户uid为: " + uid + "');</script>");
        try {
            if (uid == null) {
                out.println("您尚未登录,请先登录以查看购物车内容。");
            } else {
                List<CartItem> cartItems = bookRepo.getCartItemsByUserId(uid);

                Map<Integer, Book> bookMap = new HashMap<>();
                for (CartItem item : cartItems) {
                    Book book = bookRepo.getById(item.getBookId());
                    if (book != null) {
                        bookMap.put(item.getBookId(), book);
                    }
                }

                // CSS
                out.println("<style>");
                out.println("body { font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 0; margin-bottom: 50px;}");
                out.println("h1 { color: #333; text-align: center; }");
                out.println("h2 { color: #2c3e50; text-align: center; }");
                out.println("table { border-collapse: collapse; width: 80%; margin: 0 auto; }");
                out.println("th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }");
                out.println("th { background-color: #4CAF50; color: white; }");
                out.println("tr:nth-child(even) { background-color: #f2f2f2; }");
                out.println("tr:hover { background-color: #ddd; }");
                out.println("form { background: #fff; padding: 10px; border-radius: 5px; width: 150px; margin: 0 auto; }"); // 修改: 调整form的大小
                out.println("input[type='text'], input[type='number'] { width: 100%; padding: 8px 10px; margin: 8px 0; display: inline-block; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; }");
                out.println("input[type='submit'] { width: 100%; background-color: #4CAF50; color: white; padding: 8px 10px; margin: 8px 0; border: none; border-radius: 4px; cursor: pointer; }"); // 修改: 调整submit按钮大小
                out.println("input[type='submit']:hover { background-color: #45a049; }");
                out.println(".center-content { text-align: center; }");
                out.println("h2.total-price { color: #e74c3c; text-align: center; }");
                out.println(".total-price-container { background-color: #fff; border-radius: 5px; padding: 15px; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.15); width: 200px; position: fixed; right: 20px; top: 100px; }");
                out.println(".floating-buttons { position: fixed; right: 20px; bottom: 20px; width: 150px; }"); // 修改: 调整容器大小
                out.println(".floating-buttons form { margin-bottom: 10px; }");
                out.println(".floating-buttons input[type='submit'] { width: 100%; }");
                out.println(".pay-button { width: 100%; background-color: #e74c3c; color: white; padding: 10px 0; border: none; border-radius: 4px; cursor: pointer; margin-top: 10px; }");
                out.println(".pay-button:hover { background-color: #c0392b; }");
                out.println("</style>");


                out.println("<!DOCTYPE html>");
                out.println("<html lang='en'>");
                out.println("<head>");
                out.println("<meta charset='UTF-8'>");
                out.println("<title>购物界面</title>");
                out.println("</head>");
                out.println("<body>");

                out.println("<h1>欢迎来到购物车界面!</h1>");
                out.println("<p class='center-content'>访问时间: " + new Date() + "</p>");

                // 添加搜索表单
                out.println("<h2>搜索图书:</h2>");
                out.println("<div style='width: 300px; margin: 0 auto;'>");
                out.println("<form action='shopping' method='get'>");
                out.println("书名关键字: <input type='text' name='searchKey' required><br>");
                out.println("<input type='submit' value='搜索图书'>");
                out.println("</form>");
                out.println("</div>");

                // 显示搜索结果
                String searchKey = request.getParameter("searchKey");
                if (searchKey != null && !searchKey.isEmpty()) {
                    List<Book> searchResults = bookRepo.searchByName(searchKey);
                    out.println("<h2>搜索结果:</h2>");
                    if (searchResults.isEmpty()) {
                        out.println("<p class='center-content'>未找到相关书籍。</p>");
                    } else {
                        out.println("<table>");
                        out.println("<tr><th>ID</th><th>名称</th><th>作者</th><th>价格</th><th>备注</th><th>出版日期</th><th>操作</th></tr>");
                        for (Book book : searchResults) {
                            out.println("<tr>");
                            out.println("<td>" + book.getId() + "</td>");
                            out.println("<td>" + book.getName() + "</td>");
                            out.println("<td>" + book.getAuthor() + "</td>");
                            out.println("<td>" + book.getPrice() + "</td>");
                            out.println("<td>" + book.getMemo() + "</td>");
                            out.println("<td>" + new SimpleDateFormat("yyyy-MM-dd").format(book.getPublish()) + "</td>");
                            out.println("<td><form action='shopping' method='post'><input type='hidden' name='bookId' value='" + book.getId() + "'><input type='hidden' name='quantity' value='1'><input type='submit' value='添加到购物车'></form></td>");
                            out.println("</tr>");
                        }
                        out.println("</table>");
                    }
                }

                // 显示购物车内容
                out.println("<h2>购物车内容:</h2>");
                if (cartItems.isEmpty()) {
                    out.println("<p class='center-content'>您的购物车为空。</p>");
                } else {
                    out.println("<table>");
                    out.println("<tr><th>ID</th><th>名称</th><th>作者</th><th>价格</th><th>备注</th><th>出版日期</th><th>数量</th><th>操作</th></tr>");
                    double totalPrice = 0.0;
                    for (CartItem item : cartItems) {
                        Book book = bookMap.get(item.getBookId());
                        if (book != null) {
                            out.println("<tr>");
                            out.println("<td>" + book.getId() + "</td>");
                            out.println("<td>" + book.getName() + "</td>");
                            out.println("<td>" + book.getAuthor() + "</td>");
                            out.println("<td>" + book.getPrice() + "</td>");
                            out.println("<td>" + book.getMemo() + "</td>");
                            out.println("<td>" + new SimpleDateFormat("yyyy-MM-dd").format(book.getPublish()) + "</td>");
                            out.println("<td>" + item.getQuantity() + "</td>");
                            out.println("<td><form action='shopping' method='post'><input type='hidden' name='action' value='delete'><input type='hidden' name='bookId' value='" + book.getId() + "'><input type='submit' value='删除'></form></td>");
                            out.println("</tr>");
                            totalPrice += book.getPrice() * item.getQuantity();
                        }
                    }
                    out.println("</table>");

                    // 添加显示总价格的板块
                    out.println("<div class='total-price-container'>");
                    out.println("<h2 class='total-price'>购物车总价: ¥" + String.format("%.2f", totalPrice) + "</h2>");
                    out.println("<button class='pay-button' onclick='location.href=\"/bookstore/Pay.html\"'>支付</button>"); // 新增: 支付按钮
                    out.println("</div>");
                }


                out.println("<div class='floating-buttons'>");
                out.println("<form action='/bookstore/index.html' method='post'>");
                out.println("<input type='submit' value='返回首页'>");
                out.println("</form>");
                out.println("</div>");


            }
            out.println("</body>");
            out.println("</html>");
        } catch (SQLException e) {
            e.printStackTrace();
            out.println("购物车内容加载失败");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        Integer uid = (Integer) session.getAttribute("uid");

        if (uid == null) {
            response.sendRedirect("/bookstore/sign-in.html");
            return;
        }

        String action = request.getParameter("action");

        try {
            if ("delete".equals(action)) {
                int bookId = Integer.parseInt(request.getParameter("bookId"));
                bookRepo.removeFromCart(uid, bookId);
                response.sendRedirect("/bookstore/user/shopping");
            } else {
                int bookId = Integer.parseInt(request.getParameter("bookId"));
                int quantity = Integer.parseInt(request.getParameter("quantity"));

                // 检查是否已经存在相同uid和bookId的组合
                List<CartItem> existingItems = bookRepo.getCartItemsByUserIdAndBookId(uid, bookId);

                if (!existingItems.isEmpty()) {
                    // 如果存在,则不添加,跳转到错误页面
                    request.setAttribute("errorMessage", "该商品已经存在于您的购物车中,不能重复添加。");
                    request.getRequestDispatcher("/error.html").forward(request, response);
                    return;
                }

                // 如果不存在,则添加新数据
                CartItem cartItem = new CartItem(uid, bookId, quantity);
                bookRepo.addToCart(cartItem);

                // 重定向回购物页面
                response.sendRedirect("/bookstore/user/shopping");
            }
        } catch (SQLException e) {
            e.printStackTrace();

            request.setAttribute("errorMessage", "购物车操作失败,请重试。");
            request.getRequestDispatcher("/error.html").forward(request, response); // 错误时跳转回错误页面
        }
    }

}
